﻿using System.Collections.Generic;
using Report.BrowserFix;
using Report.Engine;
using Report.Entity;

namespace Report.Service
{
    public class GomezReportExporter
    {
        private ExportContext context;
        private List<IExportStep> exportSteps;

        public bool Started { get; private set; }

        public void MoveToPreviousStep()
        {
            context.CurrentIndex--;
        }

        public void MoveToNextStep()
        {
            context.CurrentIndex++;
        }

        public void Close()
        {
            Started = false;
            context = null;
            exportSteps = null;
        }

        public void PrepareContext(WebBrowserExtended gomezWebBrowser)
        {
            Started = true;
            ImageSetting imageSetting = ImageSettingManager.Instance.ReadSettingByUrl(gomezWebBrowser.Url.OriginalString);

            exportSteps = new List<IExportStep>();
            foreach (Step step in imageSetting.Steps)
            {
                switch (step.Type.ToLower())
                {
                    case "start":
                        exportSteps.Add(new StartStep(step));
                        break;
                    case "end":
                        exportSteps.Add(new EndStep());
                        break;
                    case "image":
                        exportSteps.Add(new ImageStep(step));
                        break;
                    case "mix":
                        exportSteps.Add(new ImageAndTableStep(step));
                        break;
                }
            }
            context = new ExportContext(gomezWebBrowser, imageSetting);
        }

        public void ExecuteCurrentStep()
        {
            IExportStep currentStep = exportSteps[context.CurrentIndex];

            ExecuteResult result = currentStep.Execute(context);

            if (result == ExecuteResult.NextStep)
            {
                MoveToNextStep();
            }
            else if (result == ExecuteResult.Close)
            {
                Close();
            }
        }

        public string GetCurrentStpName()
        {
            return string.Format("{0}-{1}", context.ImageSetting.Name, context.ImageSetting.Steps[context.CurrentIndex].Name);
        }
    }
}